﻿using System;
using System.Collections.Generic;
using System.Text;
using SecureConnection.Utils;


namespace RemoteCode
{
    public class Result
    {
        internal Result(bool err, Exception ex, NexumError c, object retval)
        {
            error = err;
            exception = ex;
            code = c;
            ret = retval;
        }
        internal Result()
        {
        }
        ~Result()
        {
            Dispose();
        }

        internal bool error;
        internal Exception exception;
        internal NexumError code;
        internal object ret;

        internal static Result FromByteArray(ref ByteArrayReader br)
        {
            Result r = new Result();
            r.error = br.ReadByte() == 1 ? true : false;

            int length = br.ReadInt();
            if (length != 0)
                r.exception = (Exception)SerializationHelper.Deserialize(br.ReadBytes(length));
            else r.exception = null;

            r.code = (NexumError)br.ReadByte();

            length = br.ReadInt();
            if (length != 0)
                r.ret = SerializationHelper.Deserialize(br.ReadBytes(length));
            else r.ret = null;

            return r;
        }
        internal byte[] ToByteArray()
        {
            ByteArrayWriter bw = new ByteArrayWriter();
            bw.WriteByte(error == true ? (byte)1 : (byte)0);
            byte[] buffer;
            
            if (exception != null)
            {
                buffer = SerializationHelper.Serialize(exception);

                bw.WriteInt(buffer.Length);
                bw.WriteBytes(buffer);
            }
            else { bw.WriteInt(0); }

            bw.WriteByte((byte)code);

            if (ret == null)
                bw.WriteInt(0);
            else
            {
                buffer = SerializationHelper.Serialize(ret);
                bw.WriteInt(buffer.Length);
                bw.WriteBytes(buffer);
            }
            return bw.ToByteArray();
        }
        internal void Dispose()
        {
            ret = null;
            exception = null;
        }
    }
}
